//
//  YCLabelAlertView.m
//  DemoAlertView
//
//  Created by tangkexiong on 15/9/28.
//  Copyright (c) 2015年 tangkexiong. All rights reserved.
//

#import "YCLabelAlertView.h"

@interface YCLabelAlertView () {
    UIImageView *_bgImgView;
    NSString *_title;
    NSString *_message;
    NSArray *_buttonTitles;
    UIImage *_cancelBtnImg;
    
    UIView *_alertView;
    UIView *_darknessView;
    UIView *_dlgView;
    UIView *_buttonView;
    
    NSLayoutConstraint *_dlgHeightConst;
}

@end

@implementation YCLabelAlertView

- (void)setupView {
    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height;
    
    _bgImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    _bgImgView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:_bgImgView];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_bgImgView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_bgImgView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_bgImgView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_bgImgView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
    
    _alertView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    _alertView.backgroundColor = [UIColor clearColor];
    _alertView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:_alertView];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_alertView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_alertView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_alertView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_alertView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
    
    CGFloat width_alert = _alertView.frame.size.width;
    CGFloat height_alert = _alertView.frame.size.height;
    
    _darknessView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,width_alert, height_alert)];
    _darknessView.backgroundColor = [UIColor blackColor];
    _darknessView.alpha = 0.5;
    _darknessView.translatesAutoresizingMaskIntoConstraints = NO;
    [_alertView addSubview:_darknessView];
    [_alertView addConstraint:[NSLayoutConstraint constraintWithItem:_darknessView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_alertView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
    [_alertView addConstraint:[NSLayoutConstraint constraintWithItem:_darknessView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_alertView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    [_alertView addConstraint:[NSLayoutConstraint constraintWithItem:_darknessView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:_alertView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
    [_alertView addConstraint:[NSLayoutConstraint constraintWithItem:_darknessView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:_alertView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
    
    CGFloat width_dlg = 300;
    CGFloat height_dlg = 0;
    
    _dlgView = [[UIView alloc] initWithFrame:CGRectMake((width_alert-width_dlg)/2.0, (height_alert-height_dlg)/2.0, width_dlg, height_dlg)];
    _dlgView.backgroundColor = [UIColor whiteColor];
    _dlgView.layer.cornerRadius = 5.0f;
    _dlgView.translatesAutoresizingMaskIntoConstraints = NO;
    [_alertView addSubview:_dlgView];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:_dlgView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:width_dlg]];
    _dlgHeightConst = [NSLayoutConstraint constraintWithItem:_dlgView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:height_dlg];
    [_dlgView addConstraint:_dlgHeightConst];
    [_alertView addConstraint:[NSLayoutConstraint constraintWithItem:_dlgView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:_alertView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [_alertView addConstraint:[NSLayoutConstraint constraintWithItem:_dlgView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:_alertView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 13, width_dlg-15-15, 20)];
    _titleLabel.textColor = [UIColor colorWithRed:220/255.0 green:3/255.0 blue:20/255.0 alpha:1.0];
    _titleLabel.text = _title;
    _titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [_dlgView addSubview:_titleLabel];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:_titleLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_dlgView attribute:NSLayoutAttributeTop multiplier:1.0 constant:8]];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:_titleLabel attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_dlgView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:15]];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:_titleLabel attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:_dlgView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:15]];
    [_titleLabel addConstraint:[NSLayoutConstraint constraintWithItem:_titleLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:20]];
    
    _cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(width_dlg-30, 0, 30, 30)];
    [_cancelBtn setImage:_cancelBtnImg forState:UIControlStateNormal];
    [_cancelBtn addTarget:self action:@selector(cancelBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    _cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [_dlgView addSubview:_cancelBtn];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:_cancelBtn attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_dlgView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:_cancelBtn attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:_dlgView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
    [_cancelBtn addConstraint:[NSLayoutConstraint constraintWithItem:_cancelBtn attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:30]];
    [_cancelBtn addConstraint:[NSLayoutConstraint constraintWithItem:_cancelBtn attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:30]];
    
    _buttonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width_dlg, 40)];
    _buttonView.translatesAutoresizingMaskIntoConstraints = NO;
    [_dlgView addSubview:_buttonView];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:_buttonView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:_dlgView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:_buttonView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_dlgView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:_buttonView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:_dlgView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
    [_buttonView addConstraint:[NSLayoutConstraint constraintWithItem:_buttonView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40]];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 40, width_dlg, 1)];
    lineView.backgroundColor = [UIColor colorWithRed:124/255.0 green:124/255.0 blue:124/255.0 alpha:1.0];
    lineView.translatesAutoresizingMaskIntoConstraints = NO;
    [_dlgView addSubview:lineView];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:lineView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:_buttonView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:lineView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_dlgView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:lineView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:_dlgView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
    [lineView addConstraint:[NSLayoutConstraint constraintWithItem:lineView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:0.5]];
    
    _contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width_dlg-15-15, 100)];
    _contentLabel.font = [UIFont systemFontOfSize:15];
    _contentLabel.numberOfLines = 0;
    _contentLabel.lineBreakMode = NSLineBreakByCharWrapping;
    _contentLabel.text = _message;
    _contentLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [_dlgView addSubview:_contentLabel];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:_contentLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_cancelBtn attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:_contentLabel attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_dlgView attribute:NSLayoutAttributeLeading multiplier:1.0 constant:15]];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:_contentLabel attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:_dlgView attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:-15]];
    [_dlgView addConstraint:[NSLayoutConstraint constraintWithItem:_contentLabel attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:lineView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    
    NSInteger count = _buttonTitles.count;
    CGFloat perWidth = width_dlg/count;
    for (int i = 0; i < count; i++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(perWidth * i, 0, perWidth, 40)];
        btn.titleLabel.font = [UIFont systemFontOfSize:17];
        [btn setTitleColor:[UIColor colorWithRed:12/255.0 green:194/255.0 blue:156/255.0 alpha:1.0] forState:UIControlStateNormal];
        btn.tag = 100 + i;
        [btn addTarget:self action:@selector(otherBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTitle:_buttonTitles[i] forState:UIControlStateNormal];
        
        if (i != 0) {
            UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(perWidth * i-0.25, 0, 0.5, 40)];
            separatorView.backgroundColor = [UIColor colorWithRed:124/255.0 green:124/255.0 blue:124/255.0 alpha:1.0];
            [_buttonView addSubview:separatorView];
        }
        [_buttonView addSubview:btn];
    }
    
    [self addObserver:self forKeyPath:@"_contentLabel.text" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    [self addObserver:self forKeyPath:@"_contentLabel.attributedText" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    
    CGRect rect = [_message boundingRectWithSize:CGSizeMake(width_dlg-15-15, 500) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:_contentLabel.font} context:nil];
    
    _dlgHeightConst.constant = rect.size.height + 53 + 40;
    [self.view layoutIfNeeded];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"_contentLabel.text"]) {
        _message = change[NSKeyValueChangeNewKey];
        
        CGRect rect = [_message boundingRectWithSize:CGSizeMake(300-15-15, 500) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:_contentLabel.font} context:nil];
        
        _dlgHeightConst.constant = rect.size.height + 53 + 40;
        [self.view layoutIfNeeded];
    } else if ([keyPath isEqualToString:@"_contentLabel.attributedText"]) {
        NSAttributedString *attrStr = change[NSKeyValueChangeNewKey];
        _message = attrStr.string;
        
        CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(300-15-15, 500) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
        
        _dlgHeightConst.constant = rect.size.height + 53 + 40;
    }
    
    [self.view layoutIfNeeded];
}

#pragma mark - Public Methods

- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id<YCLabelAlertViewDelegate>)delegate cancelButtonImg:(UIImage *)cancelButtonImg otherButtonTitles:(NSString *)otherButtonTitles, ... {
    self = [super init];
    
    if (self) {
        _title = title;
        _message = message;
        _myDelegate = delegate;
        _cancelBtnImg = cancelButtonImg;
        NSMutableArray *array = [[NSMutableArray alloc] init];
        va_list args;
        va_start(args, otherButtonTitles);
        if (otherButtonTitles) {
            NSString *str;
            [array addObject:otherButtonTitles];
            while ((str=va_arg(args, NSString *))) {
                [array addObject:str];
            }
        }
        va_end(args);
        _buttonTitles = array;
        
        [self setupView];
    }
    
    return self;
}

- (void)showInViewController:(UIViewController *)vc {
    [_bgImgView setImage:[self snapshotOfScreenNoStatusInViewController:vc]];
    
    self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [vc presentViewController:self animated:YES completion:nil];
}

#pragma mark - Button Click

- (void)cancelBtnClicked:(UIButton *)btn {
    if ([self.myDelegate respondsToSelector:@selector(labelAlertViewClickedCancelButton:)]) {
        [self.myDelegate labelAlertViewClickedCancelButton:self];
    }
}

- (void)otherBtnClicked:(UIButton *)btn {
    if ([self.myDelegate respondsToSelector:@selector(labelAlertView:clickedButtonAtIndex:)]) {
        [self.myDelegate labelAlertView:self clickedButtonAtIndex:btn.tag-100];
    }
}

#pragma mark - Other Methods

- (UIImage *)snapshotOfScreenNoStatusInViewController:(UIViewController *)vc {
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    UIGraphicsBeginImageContextWithOptions(vc.view.window.bounds.size, YES, 0.0);
    [vc.view.window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
    return image;
}

@end
